<?php

function sdebug($object){  
  $fh = fopen('sdebug.txt', 'a+') or die("Can't open file.");
  $results = print_r($object, true);
  fwrite($fh, $results);
  fclose($fh);
}

function get_term_name_by_tid($tid){
    return db_query('SELECT name FROM taxonomy_term_data WHERE tid=:tid', array(':tid'=>$tid))->fetchField();
}

// receive ajax request and response
function process_ajax(){
    $action = $_REQUEST['action'];
    switch($action){
        case 'addToCart':
//            if(user_is_anonymous()){
//                echo "-";
//                return;
//            }           
            $nid = filter_xss($_REQUEST['nid']);
            $amount = filter_xss($_REQUEST['amount']);
            $size = filter_xss($_REQUEST['size']);
            $color = filter_xss($_REQUEST['color']);
            $arr_order_detail = array();
            if(isset($_SESSION[SESSION_CART])){
                $arr_order_detail = unserialize( @$_SESSION[SESSION_CART]);
            }
            
            $add_new = true;
            foreach($arr_order_detail as &$order_detail){
                if($order_detail->ref_nid == $nid){ // seleted product existed, just increase amount
                    $order_detail->amount += $amount;
                    $add_new = false;
                }
            }
            if($add_new){
                $new_order_detail = new OrderDetail();
                $product = new Product($nid);            
                $new_order_detail->ref_nid = $product->nid;
                $new_order_detail->ref_id = $product->id;
                $new_order_detail->title = $product->title;
                $new_order_detail->color = $color;
                $new_order_detail->size = $size;
                $new_order_detail->amount = $amount;
                $arr_order_detail[]=$new_order_detail;
            }
            $_SESSION[SESSION_CART]=  serialize($arr_order_detail);            
            break;
            
        case 'removeFromCart':
            $nid = filter_xss($_REQUEST['nid']);
            $arr_order_detail = array();
            if(isset($_SESSION[SESSION_CART])){
                 $arr_order_detail = unserialize( @$_SESSION[SESSION_CART]);
            }
            foreach($arr_order_detail as $order_detail){
                if($order_detail->ref_nid == $nid){ // remove this order from cart         
                    $key = array_search($order_detail, $arr_order_detail);
                    unset($arr_order_detail[$key]);
                }
            }
            $_SESSION[SESSION_CART]=  serialize($arr_order_detail);                  
            break;
            
        case 'reloadBlockCarts':
            echo display_block_cart();
            break;
        
        case 'updateCart':
            $nid = filter_xss($_REQUEST['nid']);
            $size = filter_xss($_REQUEST['size']);
            $amount = filter_xss($_REQUEST['amount']);
            $arr_order_detail = array();
            if(isset($_SESSION[SESSION_CART])){
                 $arr_order_detail = unserialize( $_SESSION[SESSION_CART]);
            }
            foreach($arr_order_detail as &$order_detail){
                if($order_detail->ref_nid==$nid){
                    if($size!=NULL)
                        $order_detail->size=$size;
                    if($amount!=NULL)
                        $order_detail->amount=$amount;                    
                }
            }
             $_SESSION[SESSION_CART]=  serialize($arr_order_detail);         
             echo "1";
            break;
        
        case 'addComment':
            if(user_is_anonymous()){
                echo "-";
                return;
            }
            $title = filter_xss($_REQUEST['title']);
            $body = filter_xss($_REQUEST['body']);
            $nid = filter_xss($_REQUEST['nid']);
            $comment = new stdClass();
            $comment->nid = $nid;
            $comment->uid = $GLOBALS['user']->uid;
            $comment->subject = $title;
            $comment->comment_body[LANGUAGE_NONE][0]['value'] = $body;
            try{
                comment_save($comment);
                $comment = comment_load($comment->cid);
                echo display_comment($comment);
            }catch(Exception $e){
                echo "0";
            }
            break;
            
        case 'popupProduct':
            $nid = $_REQUEST['nid'];
            $product = new Product($nid);
            echo $product->display_product_info(true);
            break;
        
         case 'custom_search':
            $key = filter_xss($_REQUEST['key']);
             if($key==''){
                 return;
             }
            $result = '';
            $count=0;
            
            // search in brands
            $brands = db_query("SELECT * FROM taxonomy_term_data WHERE vid=:vid AND name LIKE :name",
                    array(':vid'=>VID_PRODUCT_BRAND, ':name'=> '%'.$key.'%'))->fetchAll();
            foreach($brands as $brand){
                if($count<10){
                    $query = array('brand'=>$brand->tid);
                    $result.='<div class="result"><a href="'.url('search-product', array('query'=>$query)).'">'.$key.' <span>trong</span> '.$brand->name.'</a></div>';
                    $count++;
                }else{
                    echo $result;
                    return;
                }                    
            }
            
            // search in category
            if($count<10){
               $categories = db_query("SELECT * FROM taxonomy_term_data WHERE vid=:vid AND name LIKE :name",
                       array(':vid'=>VID_PRODUCT_CATEGORY, ':name'=> '%'.$key.'%'))->fetchAll();
               foreach($categories as $category){
                   if($count<10){
                       $result.='<div class="result"><a href="'.url('taxonomy/term/'.$category->tid).'">'.$key.' <span>trong</span> '.$category->name.'</a></div>';
                       $count++;
                   }else{
                       echo $result;
                       return;
                   }                    
               }   
            }
            
            // search in title
            if($count<10){
                $products = db_query("SELECT * FROM node WHERE TYPE='product' AND status=1 AND title LIKE :name",
                        array(':name'=>'%'.$key.'%'))->fetchAll();
                foreach($products as $product){
                    if($count<10){
                       $result.='<div class="result"><a href="'.url('node/'.$product->nid).'">'.$key.' <span>trong</span> '.$product->title.'</a></div>';
                       $count++;
                   }else{
                       echo $result;
                       return;
                   }      
                }
            }
            
            // search in product id
            if($count<10){
                $products = db_query("SELECT n.title, n.nid FROM node n, field_data_field_product_id f WHERE f.bundle='product' AND f.field_product_id_value LIKE :name AND f.entity_id=n.nid AND n.status=1",
                        array(':name'=>'%'.$key.'%'))->fetchAll();
                foreach($products as $product){
                    if($count<10){
                       $result.='<div class="result"><a href="'.url('node/'.$product->nid).'">'.$key.' <span>trong</span> '.$product->title.'</a></div>';
                       $count++;
                   }else{
                       echo $result;
                       return;
                   }      
                }
            }
            
            echo $result;
            break;
    }
    
    die;
}

function get_products_highest_rating($tid = NULL) {    
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'product')
            ->propertyCondition('status', 1)
            ->fieldOrderBy('field_rate', 'rating', 'DESC')
            ->range(0, 9);
    if ($tid != NULL) {
        $arr_tid=  get_children_tid($tid);
        $query->fieldCondition('field_product_category', 'tid', $arr_tid, 'in');
    }    

    $result = $query->execute();
    $products = array();
    if (isset($result['node'])) {
        foreach ($result['node'] as $tmp) {
            $p = new Product($tmp->nid);
            $products[] = $p;
        }
    }
    return $products;
}

function get_products_sale_off($tid = NULL) {        
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'product')
            ->propertyCondition('status', 1)            
           ->fieldCondition('field_listed_price', 'value', 0, '!=')
            ->fieldOrderBy('field_rate', 'rating', 'DESC')
            ->range(0, 4);
    if ($tid != NULL) {
        $arr_tid=  get_children_tid($tid);
        $query->fieldCondition('field_product_category', 'tid', $arr_tid, 'in');
    }
    $result = $query->execute();
    
    $products = array();
    if (isset($result['node'])) {
        foreach ($result['node'] as $tmp) {
            $p = new Product($tmp->nid);
            $products[] = $p;
        }
    }
    return $products;
}

/**
 * Return array of term id, include the input tid
 */
function get_children_tid($tid){
    $terms = taxonomy_get_children($tid);
    $arr_tid = array($tid);
    foreach($terms as $term){
        $arr_tid[]=$term->tid;
    }
    return $arr_tid;
}

//function get_user_avatar($uid){
//    return db_query('SELECT uri FROM file_managed WHERE fid=(SELECT field_user_avatar_fid FROM field_data_field_user_avatar WHERE entity_id=:uid)',
//                array(':uid'=>$uid))->fetchField();
//}

function get_products_in_category($tid, $n=10){
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'product')
            ->propertyCondition('status', 1)            
            ->fieldOrderBy('field_rate', 'rating', 'DESC')
            ->range(0, $n);
    if ($tid != NULL) {
        $arr_tid=  get_children_tid($tid);
        $query->fieldCondition('field_product_category', 'tid', $arr_tid, 'in');
    }
    $result = $query->execute();
    
    $products = array();
    if (isset($result['node'])) {
        foreach ($result['node'] as $tmp) {
            $p = new Product($tmp->nid);
            $products[] = $p;
        }
    }
    return $products;
}

function get_brand_by_category($tid_category){
    $childrens = get_children_tid($tid_category);
    return db_query("SELECT field_product_brand_tid as tid FROM field_data_field_product_brand WHERE entity_id IN "
            . "(SELECT entity_id FROM field_data_field_product_category "
            . " WHERE entity_type='node'  AND bundle='product' "
            . " AND field_product_category_tid in (:arr_category)) GROUP BY tid", array(':arr_category'=>$childrens))->fetchCol();
}

function client_info_form($form, &$form_state){
    $form['name']=array(
        '#type' => 'textfield',
        '#title' => 'Họ tên',
        '#required' => true
    );
    
    $form['city']=array(
        '#type' => 'select',
        '#options' => array('Hồ Chí Minh'),
        '#required' => true,
        '#title' => 'Tỉnh/ Thành'
    );
    
    $form['phone']=array(
        '#type' => 'textfield',
        '#title' => 'Số điện thoại',
        '#required' => true
    );    
    
    $form['district']=array(
        '#type' => 'select',
        '#options' => get_arr_district_in_HCM(),
        '#required' => true,
        '#title' => 'Quận/ Huyện'
    );
    
    $form['email']=array(
        '#type' => 'textfield',
        '#title' => 'Email',
        '#required' => true
    );    
    
    $form['address']=array(
        '#type' => 'textfield',
        '#title' => 'Địa chỉ',
        '#required' => true
    );    
    
    $form['note']=array(
        '#type' => 'textarea',
        '#title' => 'Ghi chú',        
    );  
    return $form;
}

function get_arr_district_in_HCM(){
    $arr_district = array();
    for($i=1; $i<=12; $i++){
        $arr_district[]='Quận '.$i;
    }
    $arr_district[]='Quận Phú Nhuận';
    $arr_district[]='Quận Gò Vấp';
    $arr_district[]='Quận Bình Thạnh';
    $arr_district[]='Quận Tân Bình';
    $arr_district[]='Quận Bình Tân';
    return $arr_district;
}

/**
 * Xử lý khi user xác nhận đặt đơn hàng
 */
function process_add_order(){
    if(isset($_REQUEST['btnSubmit'])){
        // 1. save 'Thông tin người mua' vào user hiện tại để lần sau load lên
        if(user_is_logged_in()){
            $user = user_load($GLOBALS['user']->uid);
            $user->field_full_name[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['name-buyer']);
            $user->field_city[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['city-buyer']);
            $user->field_district[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['district-buyer']);
            $user->field_phone[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['phone-buyer']);
            $user->field_address[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['address-buyer']);
            user_save($user);
        }
        
        // 2. save đơn hàng
        $order = new stdClass();
        $order->type='order';
        $order->title='Đơn hàng số '.REQUEST_TIME;
        
        
        $order->field_full_name[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['name-buyer']);
        $order->field_city[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['city-buyer']);
        $order->field_district[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['district-buyer']);
        $order->field_phone[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['phone-buyer']);
        $order->field_address[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['address-buyer']);
        $order->field_email[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['email-buyer']);
        
        $info_type = $_REQUEST['transform']==1? 'buyer':'receive';
        $order->field_full_name_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['name-'.$info_type]);
        $order->field_city_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['city-'.$info_type]);
        $order->field_district_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['district-'.$info_type]);
        $order->field_phone_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['phone-'.$info_type]);
        $order->field_address_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['address-'.$info_type]);
        $order->field_email_receive[LANGUAGE_NONE][0]['value']=  filter_xss($_REQUEST['email-'.$info_type]);
        if(user_is_logged_in()){
            $order->uid=$GLOBALS['user']->uid;
        }
        if($_REQUEST['transform']==1)
            $order->field_buy_as_receiver[LANGUAGE_NONE][0]['value']=1;
        
        node_save($order);
        
        // 3. save các chi tiết đơn hàng từ session
        if (isset($_SESSION[SESSION_CART])) {
            $arr_order_detail = unserialize($_SESSION[SESSION_CART]);
        }
        $i=1;
        $total_cost = 0;
        foreach ($arr_order_detail as $order_detail) {
            $n_order_detail = new stdClass();
            $n_order_detail->type='order_detail';
            $n_order_detail->title='Chi tiết '.$order->title.' - '.$i;
            $n_order_detail->field_reference_product_nid[LANGUAGE_NONE][0]['nid']=$order_detail->ref_nid;
            $product = new Product($order_detail->ref_nid);
            $n_order_detail->field_reference_product_id[LANGUAGE_NONE][0]['value']=$product->id;
            $n_order_detail->field_amount[LANGUAGE_NONE][0]['value']=$order_detail->amount;
            $n_order_detail->field_color[LANGUAGE_NONE][0]['rgb']=$order_detail->color;
            $n_order_detail->field_size[LANGUAGE_NONE][0]['value']=$order_detail->size;
            $n_order_detail->field_ref_order[LANGUAGE_NONE][0]['nid']=$order->nid;            
            $n_order_detail->field_sell_price[LANGUAGE_NONE][0]['value']= $product->sell_price;
            node_save($n_order_detail);
            
            $total_cost += $order_detail->amount * $product->sell_price;
            $i++;
        }
        // update lại tổng giá cho đơn hàng
        $order->field_total_cost[LANGUAGE_NONE][0]['value']=$total_cost;
        node_save($order); 
        
        // 4. gửi mail, etc.....
        
        // 5. xóa session
        unset($_SESSION[SESSION_CART]);
        
        drupal_set_message('Cảm ơn bạn đã đặt hàng. Chúng tôi đã ghi nhận và sẽ liên lạc lại với bạn');
        drupal_goto();
    }
}

/**
 * Search products then display on search page
 * category
 * brand
 * usage
 * material
 * color
 * price (array)
 * saving (array)
 * sort: latest|lowestprice|hightestprice|saving|rating|sticky
 */
function search_product($limit=0){
    $params = drupal_get_query_parameters();
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'product')
            ->propertyCondition('status', 1);            
    if($limit!=0){
        $query->pager($limit);
    }
    
    if(isset($params['category'])){
        $arr_tid = get_children_tid($params['category']);
        $query->fieldCondition('field_product_category', 'tid', $arr_tid, 'in');
    }
    
    if(isset($params['brand'])){
        $query->fieldCondition('field_product_brand', 'tid', $params['brand'], '=');
    }
    
    if(isset($params['usage'])){
        $query->fieldCondition('field_product_usage', 'tid', $params['usage'], '=');
    }
    
    if(isset($params['material'])){
        $query->fieldCondition('field_product_material', 'tid', $params['material'], '=');
    }
    
    if(isset($params['color'])){
        $query->fieldCondition('field_color', 'rgb', $params['color'], '=');
    }
    
    if(isset($params['price'])){
        $query->fieldCondition('field_sell_price', 'value', $params['price'], 'between');
    }
    
    if(isset($params['saving'])){
        $query->fieldCondition('field_saving', 'value', $params['saving'], 'between');
    }
    
    if(isset($params['sort'])){
        switch($params['sort']){
            // sort: latest|lowestprice|hightestprice|saving|rating|sticky
            case 'lastest':
                $query->propertyOrderBy('created', 'DESC');
                break;
            case 'lowestprice':
                $query->fieldOrderBy('field_sell_price', 'value', 'ASC');
                break;
            case 'hightestprice':
                $query->fieldOrderBy('field_sell_price', 'value', 'DESC');
                break;
            case 'saving':
                $query->fieldOrderBy('field_saving', 'value','DESC');
                break;
            case 'rating':
                $query->fieldOrderBy('field_rate', 'rating', 'DESC');
                break;
            
            // special: not order, filter it
            case 'sticky':
                $query->propertyCondition('sticky', 1);
                break;            
        }        
    }
    
    $result = $query->execute();   
    
     if($limit==0){
         if(isset($result['node']))
             return count($result['node']);
         else
             return 0;
     }
     
    $products = array();
    if (isset($result['node'])) {
        
        foreach ($result['node'] as $tmp) {
            $p = new Product($tmp->nid);
            $products[] = $p;
        }
    }
    return $products;   
}

function user_has_role($role) {   
    global $user;
    if (in_array($role, array_values($user->roles)))
        return true;
    return false;
}
